import React, { useState, useMemo, useEffect } from 'react';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import SearchIcon from '@material-ui/icons/Search';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import { NuiDlg, TextWhite, obj_str, is_empty, ErrView, MTable } from 'sui';

const SmallInput = ({ value, label, name }) => <TextWhite
    className="w-full"
    variant="outlined"
    name={name}
    disabled={true}
    value={value ? value : ""}
    type="text"
    margin="dense"
    label={label}/>;

const IkInput = ({ href, className, form, value, label, name, width="w-64", mg="normal", disabled, type="text", hkey }) => (
    <div className={className}>
        <TextField
            inputRef={href}
            disabled={disabled}
            margin={mg}
            variant="outlined"
            type={type}
            className={width}
            name={name}
            error={Boolean(form.err[name])}
            helperText={obj_str(form.err, name)}
            value={obj_str(value, name)}
            onChange={event => form.hcmd(event.target.name, event.target.value)}
            onKeyPress={hkey ? (v) => hkey(v.key) : null}
            label={label}/>
    </div>
);

const Input = ({ className, setValue, value, label, name, width="w-64", mg="normal", disabled }) => (
    <div className={className}>
        <TextField
            disabled={disabled}
            margin={mg}
            variant="outlined"
            type="text"
            className={width}
            name={name}
            value={value ? value : ""}
            onChange={event => setValue(event.target.value)}
            label={label}/>
    </div>
);

const WInput = ({ href, className, form, value, label, name, width="w-64", mg="normal" }) => (
    <div className={className}>
        <TextWhite
            inputRef={href}
            margin={mg}
            variant="outlined"
            type="text"
            className={width}
            name={name}
            error={Boolean(form.err[name])}
            helperText={obj_str(form.err, name)}
            value={obj_str(value, name)}
            onChange={event => form.hcmd(event.target.name, event.target.value)}
            label={label}/>
    </div>
);

/*
 * lst = [
 *     {id: "x", sn: "x", name: "x"}
 * ]
 */
const IkFind = ({ hcmd, className, form, value, label, name, width="w-64", dlgw="sm", dlgst="", mg="normal", fullWidth=true, lst, col }) => {
    const [open, setOpen] = useState(false);
    const [row, setRow] = useState();
    const [cur, setCur] = useState();
    const [err, setErr] = useState();

    useEffect(() => {
        if (!open) {
            return;
        }

        if (is_empty(lst)) {
            return;
        }

        setCur(obj_str(value, name));
        setRow(lst);
        setErr("");
    }, [open, lst, name, value]);

    const getView = useMemo(() => {
        if (!open) {
            return null;
        }

        const getCl = (d) => {
            if (cur === d.id) {
                return "#FEEBC8";   // orange-200
            }

            return '#FFF';
        };

        const getCol = () => {
            if (col) {
                return col;
            }

            return [
                {title: "SN", field: 'sn'},
                {title: "描述", field: 'name'},
            ];
        };

        return (
            <MTable
                title={<ErrView err={err}/>}
                opt={{
                    rowStyle: d => ({
                        backgroundColor: getCl(d)
                    }),
                }}
                hclick={(v) => setCur(v.id)}
                page={7}
                col={getCol()}
                row={row}
                exbt={false} />
        );
    }, [open, col, err, row, cur]);

    const hdone = () => {
        if (!cur) {
            return;
        }

        setOpen(false);
        form.hcmd(name, cur);

        if (hcmd) {
            hcmd(cur);
        }
    };

    const getVal = () => {
        if (is_empty(lst)) {
            return "";
        }

        const id = obj_str(value, name);
        const f = lst.find(d => d.id === id);
        if (!f) {
            return "";
        }

        let v = obj_str(f, "sn");
        const t = obj_str(f, "name");
        if (t) {
            v = `${v} ( ${t} )`;
        }

        return v;
    };

    const getInfo = () => {
        const info = obj_str(form.err, name);
        if (info) {
            return <FormHelperText>{info}</FormHelperText>;
        }

        return null;
    };

    const sz = mg === "dense" ? "small" : "medium";

    return (
        <div className={className}>
            <FormControl margin={mg} variant="outlined" className={width} error={Boolean(form.err[name])}>
                <InputLabel>{label}</InputLabel>
                <OutlinedInput
                    disabled={true}
                    name={name}
                    type="text"
                    value={getVal()}
                    endAdornment={
                        <InputAdornment position="end">
                            <IconButton size={sz} onClick={() => setOpen(true)} name={`btn${name}`}>
                                <SearchIcon fontSize={sz}/>
                            </IconButton>
                        </InputAdornment>
                    }
                    label={label}
                />
                {getInfo()}
            </FormControl>
            <NuiDlg open={open} hcancel={() => setOpen(false)} title={label} hcmd={hdone} width={dlgw} fullWidth={fullWidth} name={`bt${name}`}>
                {getView}
            </NuiDlg>
        </div>
    );
};

export {IkFind, WInput, Input, IkInput, SmallInput};
